# -*- coding:utf-8 -*-
import os
import yaml
from yaml.parser import ParserError
from config.config import extract_path, log_separator, root_path
from utils.logger import log
from utils.Tools import get_path

"""
yaml文件相关操作的封装:
读取extract.yaml的中间参数
写入参数到extract.yaml
清空extract.yaml的中间参数
提供路径读取文件内容
"""


# 中间文件，存放临时数据，用于接口间参数的传递
def read_center_params(file_path=extract_path):
    """
    读取extract.yaml的全部内容
    :return:
    """
    try:
        with open(file_path, encoding="utf-8") as f:
            result = yaml.load(f, Loader=yaml.FullLoader)
        log.info("读取文件成功 (%s). 读取内容为:\n%s" % (file_path, str(result)))
        return result
    except FileNotFoundError as Fe:
        log.error("文件路径有问题，路径为:%s" % file_path)
        raise Fe


def write_center_params(data, file_path=extract_path):
    """
    写入参数到extract.yaml
    :param file_path: 存储参数文件地址
    :param data: 写入的内容
    :return:
    """
    content = read_center_params()
    # 获取已有的参数，覆盖掉重复变量名称对应的值
    if not content:
        content = data
    else:
        for each in data.keys():
            content[each] = data[each]
    with open(file_path, "w", encoding='utf-8') as f:
        yaml.dump(data=content, stream=f, allow_unicode=True)
        log.info("文件(%s)已写入内容:\n%s" % (file_path, str(data)))


def clear_center_params(file_path=extract_path):
    """
    清空extract.yaml文件
    :return:
    """
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as r_f:
            content = yaml.load(r_f, Loader=yaml.FullLoader)
            log.info("从接口提取出来的数据为：%s\n\t" % str(content))
        with open(file_path, 'w') as f:
            f.truncate()
        log.info("文件 (%s) 清除操作已完成" % file_path)
    else:
        log.warning(
            "无法清除文件。检查路径是否存在: %s" % file_path)


# 读取yaml文件
def read_file(file_path):
    """
    读取指定路径的文件内容
    :param file_path:Yaml文件的地址
    :return:
    """
    log.info(log_separator + "Load Yaml" + log_separator)
    # 异常处理，如果yaml文件不存在，则给出对应的提示信息
    try:
        # 处理路径分隔符 - 修复版本
        file_path = os.path.join(root_path, file_path)
        # 确保路径使用正确的分隔符，不进行额外的标准化
        if os.name == 'nt':  # Windows系统
            file_path = file_path.replace('/', os.sep)
        else:  # Unix/Linux系统
            file_path = file_path.replace('\\', os.sep)
        # 读取yaml文件
        with open(file_path, encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
        log.info("读取YAML文件（%s），结果为:\n %s" % (
            file_path, str(data)))
        log.info("YAMl（%s）文件读取完成" % file_path)
        return data
    except FileNotFoundError:
        msg = "Yaml文件（%s）地址错误，请检查！" % file_path
        log.error(msg)
        raise FileNotFoundError(msg)
    except ParserError:
        msg = "Yaml文件(%s) 文件格式有问题，请检查!" % file_path
        log.error(msg)
        raise ParserError(msg)

